console.log(window["$"])
const $ = window["$"]
import router from "../router"
import config from "@/../packaging//runconfig"
import upload from "@/utils/Oss"
import download from "./download.js"
// import router from "vue-router"
// 测试模式资源数据
// ossutil32 cp ../dist/ oss://miaojia/cdn/cjcenter/convenience/ -f --config-file=./.ossutilconfig  --recursive
// market https://miaojia.oss-cn-shenzhen.aliyuncs.com/cdn/cjcenter/market/cjcenter_market.umd.js
// const userRoutesJs = [
// {
//   name: "jurisdiction",
//   moduleurl: "https://miaojia.oss-cn-shenzhen.aliyuncs.com/cdn/cjcenter/jurisdiction/cjcenter_jurisdiction.umd.js",
//   modulename: "cjcenter_jurisdiction",
//   isLoadOk: false // 加载成功后, 就需要在进行加载了
// },
//   {
//     name: "Tool",
//     moduleurl: "https://miaojia.oss-cn-shenzhen.aliyuncs.com/cdn/cjcenter/tool/cjcenter_tool.umd.min.js",
//     modulename: "cjcenter_tool",
//     isLoadOk: false // 加载成功后, 就需要在进行加载了
//   }
// ]
// 获取获取的到资源数据
const getUserRouteJs = function (obj) {
  const { name, type, url, moduleurl, modulename } = obj
  // 自带加载module信息
  if (moduleurl && modulename) {
    return obj
  }
  if (type === 0 && url.indexOf("http") === 0) {
    console.log("obj", obj)
    return {
      name: name,
      moduleurl: url,
      modulename: "cjcenter_" + name,
      isLoadOk: false
    }
  }
  if (!obj.children) {
    obj.children = []
  }
}
// 添加组件对应的公共resource
const moduleLoaderResourceList = []
// SIGN 添加对应的公共数据  ***数据将发放给子框架***
const resourceAdd = function (resource) {
  const { station, user } = router.app.$store.state
  // 当前站点cardID
  resource.companyItem = station.companyItem
  resource.cardid = station.companyItem.id
  // 添加对应的elementui调用方法
  if (!resource.elementui) resource.elementui = {}
  resource.elementui.Message = ElMessage
  resource.token = user.loginToken
  resource.topId = user.loginTopId
  resource.location_origin = config.location_origin
  moduleLoaderResourceList.push(resource)
}
// 更新公共数据
export const resourceSet = function (name, value) {
  moduleLoaderResourceList.map(function (item) {
    item[name] = value
    item.onchange && item.onchange(name, value)
  })
}
// 路由数据是否存在
export const getRoutesByName = function (name) {
  const ex = common.queryArray(router.options.routes, name, "name")
  if (ex) {
    return common.routerName2Obj[name] || ex
  }
  return null
}
export const common = {
  // 首屏需要加载的
  pagepreload: false,
  lastToRoute: {}, // 最后一次的route
  routerPushName: {}, // 路由是否已经push
  routerName2Obj: {}, // 路由参数的增强
  serveProcess: null, // 通讯服务server
  serveProcessBUILTS: {}, // 通讯服务内置事件
  serveProcessMessage: function () {}, // 框架通讯服务广播事件
  childrenAppSiderInitState: {}, // 子应用初始化状态
  loginUser: {}, //
  userToken: null,
  selectOrgUserPs: {},
  // iframe
  iframeOnLoad: function (name, fn) {
    // console.log(document.getElementById(name))
    const iframe = document.getElementById(name) || { onload }
    iframe.onload = fn
  },
  // 加载js
  loadScript: function (url) {
    return new Promise((resolve, reject) => {
      const script = document.createElement("script")
      script.type = "text/javascript"
      if (script.readyState) {
        // IE
        script.onreadystatechange = function () {
          if (script.readyState === "loaded" || script.readyState === "complete") {
            script.onreadystatechange = null
            resolve()
          }
        }
      } else {
        // Others
        script.onload = function () {
          console.log("complete")
          resolve()
        }
        script.onerror = function (e) {
          reject(e)
        }
      }
      script.src = url + "?t=" + new Date().getTime()
      document.getElementsByTagName("body")[0].appendChild(script)
    })
  },
  // div水平滚动
  divLevelRolling: function (yid) {
    const id = "#" + yid
    const firefox = navigator.userAgent.indexOf("Firefox") !== -1
    function MouseWheel(e) {
      e = e || window.event
      if (e.stopPropagation) {
        e.stopPropagation()
      } else {
        e.cancelBubble = true
      }
      if (e.preventDefault) {
        e.preventDefault()
      } else {
        e.returnValue = false
      }
      if (firefox) {
        if (e.detail < 0) {
          $(id).scrollLeft($(id).scrollLeft() + 60)
        } else {
          $(id).scrollLeft($(id).scrollLeft() - 60)
        }
      } else {
        if (e.wheelDelta > 0) {
          $(id).scrollLeft($(id).scrollLeft() + 60)
        } else {
          $(id).scrollLeft($(id).scrollLeft() - 60)
        }
      }
    }
    const div = document.getElementById(yid)
    firefox ? div.addEventListener("DOMMouseScroll", MouseWheel, false) : (div.onmousewheel = MouseWheel)
  },
  /**
   * 判断是否存在
   */
  isExistent: (id, val) => {
    if (!val) {
      val = null
    }
    if (id === undefined && id === null) {
      return val
    }
    const type = Object.prototype.toString.call(id)
    // console.log("type", type, id)
    if (type === "[object String]" && (id === "" || id.toLocaleUpperCase() === "UNDEFINED" || id.toLocaleUpperCase() === "NULL")) {
      return val
    } else if (type === "[object Object]" && Object.keys(id).length === 0) {
      return val
    } else if (type === "[object Array]" && id.length === 0) {
      return val
    } else if (type === "[object Null]") {
      return val
    } else if (type === "[object Undefined]") {
      return val
    }
    return true
  },
  /**
   * 数组内查询
   * @param   {array}     array
   * @param   {String}    id
   * @param   {String}    keyAlias
   * @return  {Array}
   */
  queryArray: function (array, key, keyAlias = "id", childrenAlias = "children") {
    if (!(array instanceof Array)) {
      return null
    }
    for (const _ of array) {
      if (_[keyAlias] === key) {
        return _
      }
      if (_[childrenAlias] && _[childrenAlias] instanceof Array) {
        const mm = this.queryArray(_[childrenAlias], key, keyAlias, childrenAlias)
        if (mm) {
          return mm
        }
      }
    }
    return null
  },
  /**
   * 树转数组
   * @param {*} data
   * @param {*} arr
   * @returns
   */
  expandTree: function (data = [], arr = [], _c = "children") {
    for (let i of data) {
      const obj = {}
      Object.keys(i).map(ky => {
        if (ky != _c) {
          obj[ky] = i[ky]
        }
      })
      arr.push(obj)
      if (i.hasOwnProperty(_c) && i[_c].length != 0) {
        arr = common.expandTree(i[_c], arr, _c)
      }
    }
    return arr
  },
  // 改变所有数组的某个值
  updateArray: function (array, key, value, _c = "children") {
    if (!(array instanceof Array)) {
      return null
    }
    for (const _ of array) {
      _[key] = typeof value === "function" ? value(_) : value
      if (_[_c] && _[_c] instanceof Array) {
        this.updateArray(_[_c], key, value, _c)
      }
    }
    return null
  },
  // 将所有的素组进行值追加
  updateArrayBeforeValue: function (array, key, value, childrenAlias = "children") {
    if (!(array instanceof Array)) {
      return null
    }
    for (const _ of array) {
      if ((_[key] + "").indexOf("_" + value) === -1) {
        _[key] = _[key] + "_" + value
      }
      if (_[childrenAlias] && _[childrenAlias] instanceof Array) {
        this.updateArrayBeforeValue(_[childrenAlias], key, value, childrenAlias)
      }
    }
    return null
  },
  // 对象 copy (浅拷贝方法)
  deepClone: function (source) {
    if (!source && typeof source !== "object") {
      return source
    }
    const targetObj = Array.isArray(source) ? [] : {}
    Object.keys(source).forEach(keys => {
      if (source[keys] && typeof source[keys] === "object") {
        targetObj[keys] = this.deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    })
    return targetObj
  },
  // 判断数据类型
  typeofFunc: data => {
    return Object.prototype.toString.call(data)
  },
  // 获取URLhash值
  getHashValue() {
    var matches = location.hash.match(new RegExp("#([^&]*)"))
    return matches ? matches[1] : null
  },
  // 生成一个token
  getuid(num) {
    var id = ""
    var uid = function () {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    for (var i = 0; i < (num || 5); i++) {
      id += uid()
    }
    return id
  },
  // 数字转中文
  numToChinese(num) {
    if (!/^\d*(\.\d*)?$/.test(num)) {
      alert("Number is wrong!")
      return "Number is wrong!"
    }
    const AA = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"]
    const BB = ["", "十", "百", "千", "万", "亿", "点", ""]
    const a = ("" + num).replace(/(^0*)/g, "").split(".")
    let k = 0
    let re = ""
    for (let i = a[0].length - 1; i >= 0; i--) {
      switch (k) {
        case 0:
          re = BB[7] + re
          break
        case 4:
          if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0])) re = BB[4] + re
          break
        case 8:
          re = BB[5] + re
          BB[7] = BB[5]
          k = 0
          break
      }
      if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re
      if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re
      k++
    }
    if (a.length > 1) {
      ww
      // 加上小数部分(如果有小数部分)
      re += BB[6]
      for (let j = 0; j < a[1].length; j++) re += AA[a[1].charAt(j)]
    }
    return re.replace(/^一十/, "十")
  },
  // 所有的子应用系统初始化
  // 注意: 这里的this, 将由调用方决定
  childrenAppSiderInit() {
    const name = this.sider.name
    // console.log("childrenAppSiderInit", name)
    if (common.childrenAppSiderInitState[name]) {
      return
    }
    common.childrenAppSiderInitState[name] = this.sider
    // 找到路由对应的菜单
    let routes = common.queryArray(this.$router.options.routes, name, "name")
    // 如果没有找到挂载的节点, 则默认挂载到root目录
    if (!routes) {
      routes = { children: [] }
    }
    routes = common.deepClone(routes)
    // 获取System对应的系统
    if (!common.isExistent(this.sider.systemItem)) {
      const systemList = this.$store.state.app.systemList
      this.sider.systemItem = systemList.filter(item => item.name === name)[0]
      this.sider.systemItem.systemItem.id = this.sider.systemItem.id
    }
    this.sider.token = this.sider.systemItem.iframe.token
    // 将对应的菜单ID增加token标记
    this.sider.data = this.sider.data.concat(routes.children || [])
    common.updateArray(this.sider.data, "id", _ => {
      return this.sider.systemItem.id + "_" + common.getuid(2)
    })
    // 进行界面菜单注册 , 这里是注册到 , system模块中
    this.sider.noSetPageHome = true // 不需要设置home
    console.log("--this.sider--", this.sider)
    // 如果有需要更新的菜单, 则需要更新
    if (this.sider.data.length > 0) {
      // console.log("common.serveProcessBUILTS.setSiderList(this.sider)", this.sider)

      common.serveProcessBUILTS.setSiderList(this.sider)
    }
  },
  // 主要
  mainAppSiderInit(item, state) {
    const name = item.url
    // 找到路由对应的菜单
    console.log("mainAppSiderInit", item.token, item)
    let routes = common.queryArray(router.options.routes, name, "name")
    // 如果没有找到挂载的节点, 则默认挂载到root目录
    if (!routes) {
      routes = { children: [] }
    }
    routes = common.deepClone(routes)
    // 获取System对应的系统
    if (!common.isExistent(item.systemItem)) {
      const systemList = state.systemList
      item.systemItem = systemList.filter(item => item.name === name)[0] || {}
    }
    // 将对应的菜单ID增加token标记
    item.data = common.deepClone(routes.children)
    common.updateArray(item.data, "id", _ => {
      return item.id + "_" + common.getuid(2)
    })
    // console.log("item.data", item.token)
    common.updateArray(item.data, "token", _ => {
      // console.log("item.token", item.name, item.token)
      return item.token
    })
    // 进行界面菜单注册 , 这里是注册到 , system模块中
    item.noSetPageHome = true // 不需要设置home
    // 如果有需要更新的菜单, 则需要更新
    item.siderList = item.data
    // 需要将更新后的路由地址 , 进行保存
    item.siderList.map(d => {
      common.routerName2Obj[d.name] = d
    })
    console.log("--item--", item, item.siderList)
  },
  // 是否是当前界面的刷新 , 并获取token
  currentRefreshPage(bool) {
    // if (!window.name || !window.name.startsWith("cjcenter_")) {
    //   return false
    // }
    // const token = window.name.split("cjcenter_")[1]
    const token = localStorage.getItem("loginToken")
    return token
  },
  /**
   * 转参数
   */
  queryParams(data = {}, isPrefix = true, arrayFormat = "brackets") {
    const prefix = isPrefix ? "?" : ""
    const _result = []
    if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) === -1) arrayFormat = "brackets"
    for (const key in data) {
      const value = data[key]
      // 去掉为空的参数
      if (["", undefined, null].indexOf(value) >= 0) {
        continue
      }
      // 如果值为数组，另行处理
      if (value.constructor === Array) {
        // e.g. {ids: [1, 2, 3]}
        switch (arrayFormat) {
          case "indices":
            // 结果: ids[0]=1&ids[1]=2&ids[2]=3
            for (let i = 0; i < value.length; i++) {
              _result.push(key + "[" + i + "]=" + value[i])
            }
            break
          case "brackets":
            // 结果: ids[]=1&ids[]=2&ids[]=3
            value.forEach(_value => {
              _result.push(key + "[]=" + _value)
            })
            break
          case "repeat":
            // 结果: ids=1&ids=2&ids=3
            value.forEach(_value => {
              _result.push(key + "=" + _value)
            })
            break
          case "comma":
            // 结果: ids=1,2,3
            // eslint-disable-next-line no-case-declarations
            let commaStr = ""
            value.forEach(_value => {
              commaStr += (commaStr ? "," : "") + _value
            })
            _result.push(key + "=" + commaStr)
            break
          default:
            value.forEach(_value => {
              _result.push(key + "[]=" + _value)
            })
        }
      } else {
        _result.push(key + "=" + value)
      }
    }
    return _result.length ? prefix + _result.join("&") : ""
  },
  // 获取可用的tab
  getAvailableTab: function (tab) {
    if (!tab) {
      return
    }
    if (!tab.children) {
      tab.children = []
    }
    // !tab.url &&
    if (tab.children.length !== 0) {
      return this.getAvailableTab(tab.children[0])
    } else {
      return tab
    }
  },
  // 路由模块是否需要进行远程加载
  routeIsLoad: function (obj, next) {
    const { name } = obj
    const item = getUserRouteJs(obj)
    const app = router.app
    // console.log("router - $moduleLoader", app["$moduleLoader"])
    if (item) {
      if (!item.isLoadOk) {
        // console.log("需要下载js", name)
        // console.log("item.moduleurl", item.moduleurl)
        app["$moduleLoader"]({
          [item.modulename]: item.moduleurl
        }).then(async () => {
          item.isLoadOk = true // 标记已加载
          // 解析路由配置信息 , 进行路由合并
          // console.log("window", window, window[item.modulename])
          const { modulroutes, resource } = window[item.modulename].default(null, true)
          const { routes } = modulroutes
          // console.log("routes", routes)
          // 设置公共数据
          if (resource) {
            await resourceAdd(resource)
          }
          routes.map(s => router.options.routes[0].children.push(s))
          router.addRoutes(router.options.routes)
          // 项目加载初始化
          app.sider = {
            name: name, // 挂载系统的路由的name
            token: "",
            data: [], // 这里可以添加 , 自定义菜单 , 可以是其他iframe这种菜单
            systemItem: obj.systemItem || {} // 对应的是当前name所对应的顶部系统name
          }
          // 子框架是否需要进行请求成功后才进行加载
          if (resource.startServerIntercept) {
            console.log("resource.startServerIntercept", resource.startServerIntercept)
            resource.startServerIntercept(function () {
              console.log("主框架开始启用页面")
              common.childrenAppSiderInit.call(app)
              next ? next(name) : null
            })
          } else {
            common.childrenAppSiderInit.call(app)
            next ? next(name) : null
          }
        })
        return true
      } else {
        next ? next(name) : null
      }
    }
    return false
  },
  routerIsExtobj: {}, // 缓存查询过存在的路由地址信息
  // 检测路由地址是否存在, 并缓存存在结果
  routerIsExt: function (name) {
    if (this.routerIsExtobj[name]) {
      return this.routerIsExtobj[name]
    }
    const ex = getRoutesByName(name)
    if (ex) {
      this.routerIsExtobj[name] = ex
    }

    return ex
  },
  // 获取通讯类容
  getCJServeProcess: function () {
    return new window["CJServeProcess"]()
  },
  // 获取通讯类容
  getCJClientProces: function (pm) {
    return new window["CJClientProces"](pm)
  },
  // 获取通讯类容
  getCJProcess: function (pm, pm2) {
    return new window["CJProcess"](pm, pm2)
  },
  // 判断是否为JSON字符串
  isJSON: str => {
    if (typeof str == "string") {
      try {
        var obj = JSON.parse(str)
        if (typeof obj == "object" && obj) {
          return true
        } else {
          return false
        }
      } catch (e) {
        console.error("isJSON JSON字符串解析错误:" + e)
        return false
      }
    }
    return false
  },
  // 数据转JSON 如果数据格式为 string 就返回原数据
  dataToJSON: data => {
    const type = Object.prototype.toString.call(data)
    if (type === "[object String]") {
      return data
    } else {
      return JSON.stringify(data)
    }
  },
  // JSON转数据 如果数据格式不为 string 就返回原数据
  jsonToData: data => {
    if (!common.isJSON(data)) {
      console.error("jsonToData JSON字符串解析错误:" + data)
      return data
    } else {
      return JSON.parse(data)
    }
  },
  /**
   * 查询树状解构指定所有值, 返回单层数组
   * list : 原数组
   * arr : 返回数据
   * key : 指定查询值
   * childrens: 下级
   */
  findTreeKeyToArray: (list = [], arr = [], key = "id", childrens = "childrens") => {
    for (let item of list) {
      arr.push(item[key])
      if (item[childrens] && item[childrens].length > 0) {
        common.findTreeKeyToArray(item[childrens], arr, key, childrens)
      }
    }
    return arr
  },
  // 将date格式转为 日期格式
  formatDate: (time, format = "YYYY-MM-DD") => {
    let t = new Date(time)
    let tf = function (i) {
      return (i < 10 ? "0" : "") + i
    }
    return format.replace(/yyyy|YYYY|MM|dd|DD|hh|HH|mm|ss|SS/g, function (a) {
      switch (a) {
        case "yyyy":
        case "YYYY":
          return tf(t.getFullYear())
        case "MM":
          return tf(t.getMonth() + 1)
        case "dd":
        case "DD":
          return tf(t.getDate())
        case "hh":
        case "HH":
          return tf(t.getHours())
        case "mm":
          return tf(t.getMinutes())
        case "ss":
        case "SS":
          return tf(t.getSeconds())
      }
    })
  },
  // 获取时间距离现在多久
  timeFrom(dateTime = null, format = "yyyy-mm-dd") {
    // 如果为null,则格式化当前时间
    if (!dateTime) dateTime = Number(new Date())
    // 如果dateTime长度为10或者13，则为秒和毫秒的时间戳，如果超过13位，则为其他的时间格式
    if (dateTime.toString().length == 10) dateTime *= 1000
    let timestamp = new Date(Number(dateTime))

    let timer = (Number(new Date()) - timestamp) / 1000
    // 如果小于5分钟,则返回"刚刚",其他以此类推
    let tips = ""
    switch (true) {
      case timer < 300:
        tips = "刚刚"
        break
      case timer >= 300 && timer < 3600:
        tips = parseInt(timer / 60) + "分钟前"
        break
      case timer >= 3600 && timer < 86400:
        tips = parseInt(timer / 3600) + "小时前"
        break
      case timer >= 86400 && timer < 2592000:
        tips = parseInt(timer / 86400) + "天前"
        break
      default:
        // 如果format为false，则无论什么时间戳，都显示xx之前
        if (format === false) {
          if (timer >= 2592000 && timer < 365 * 86400) {
            tips = parseInt(timer / (86400 * 30)) + "个月前"
          } else {
            tips = parseInt(timer / (86400 * 365)) + "年前"
          }
        } else {
          tips = common.formatDate(timestamp, format)
        }
    }
    return tips
  },
  // 处理url参数
  formatUrl: function (url) {
    // const url = window.location.href
    const search = url.substring(url.indexOf("?") + 1)
    const obj = {}
    const reg = /([^?&=]+)=([^?&=]*)/g
    search.replace(reg, (rs, $1, $2) => {
      const name = decodeURIComponent($1)
      let val = decodeURIComponent($2)
      val = String(val)
      obj[name] = val
    })
    return obj
  },
  // 数据去重
  duplicate(list) {
    const is = {}
    const ls = []
    list.map(d => {
      if (!is[d.id]) {
        is[d.id] = 1
        ls.push(d)
      }
    })
    return ls
  },
  // 下载文件
  downloadFile(fileUrl) {
    if (!fileUrl) {
      return
    }
    download(fileUrl)
  }
}
// 启动总进程通讯
console.log("serveProcess...")
common.serveProcess = common.getCJServeProcess()

/** 验证并生成图片数据
 * @param Params    所有数据列表
 * @param self      当前操作 this
 * @param skipKey   需要跳过的字段（不是必传的字段）
 * @returns {Promise}
 */
export function verifyTestImages(Params, _ps, skipKey = []) {
  return new Promise((resolve, reject) => {
    let resultList = {}
    let resultIndex = 0
    console.log(Params)
    let newTest = () => {
      let nowVal = Params[resultIndex] && Params[resultIndex].val ? Params[resultIndex].val[0] : {}
      upload(nowVal, _ps)
        .then(pic => {
          if (!pic && skipKey.indexOf(Params[resultIndex].key) == -1) {
            // 如果上传图片数据为空且此条数据在不在 skipKey 中
            // message.error(Params[resultIndex].title + "，上传失败")
            reject({ msg: Params[resultIndex].title + "，上传失败" })
            resultList = {}
            resultIndex = 0
            return
          }
          resultList[Params[resultIndex].key] = pic
          ++resultIndex
          if (Object.keys(resultList).length < Params.length) {
            newTest()
          } else {
            resolve(resultList)
          }
        })
        .catch(reject)
    }

    if (Params && Params.length > 0) {
      newTest()
    } else {
      resolve({})
    }
  })
}

export const commonfuns = {
  // 改变所有数组的某个值
  updateArray: function (array, key, value, _c = "childrens") {
    if (!(array instanceof Array)) {
      return null
    }
    for (const _ of array) {
      _[key] = typeof value === "function" ? value(_) : value
      if (_[_c] && _[_c] instanceof Array) {
        this.updateArray(_[_c], key, value, _c)
      }
    }
    return null
  }
}

// 验证密码 必须包含 数字、大写字母、小写字母、特殊字符 其中任意三种及以上
export function verifyPassword(str) {
  let count = 0

  if (str) {
    if (str.length < 8 || str.length > 16) {
      return false
    }
    if (/[\u4e00-\u9fa5]/.test(str)) {
      return false
    }
    if (/\d/.test(str)) {
      count += 1
    }
    if (/[a-z]/.test(str)) {
      count += 1
    }
    if (/[A-Z]/.test(str)) {
      count += 1
    }
    if (/[~!@#$%^&*()_+`\-={}:";"<>?,.\/]/.test(str)) {
      count += 1
    }

    return count >= 3
  }
  return false
}

export function validPassword(example = false) {
  return function valid(_, value, callback) {
    if (!value) {
      callback(new Error("请输入密码"))
    } else {
      if (!verifyPassword(value)) {
        callback(new Error(`密码需要8-16位，包含大小写字符、数字、特殊字符${example ? ",例: Hetasf123" : ""}`))
      } else {
        callback()
      }
    }
  }
}
